package greendbgui

import org.springframework.dao.DataIntegrityViolationException

class ElectoralRollEntryController 
{
    def electoralRollService

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    private static final int ROWS_PER_PAGE = 50
    
    def index() 
    {
        redirect(action: "main", params: params)
    }

    
    def main() 
    {
//        log.error (params)
        
        params.max = Math.min(params.max ? params.int('max') : ROWS_PER_PAGE, 100)
        
        ElectoralRoll roll = ElectoralRoll.get (params.id)
        
        def entries = electoralRollService.getEntries (roll, params)
        
//        def rolls = electoralRollService.getAllRolls()
        def rolls = electoralRollService.getLatestRolls()
        
        [currentRoll: roll?.displayString ?: "",
         rolls: rolls,
         electoralRollEntryInstanceList: entries, 
         electoralRollEntryInstanceTotal: entries.totalCount]
    }

    // ?? this is exactly the same as main, because I get an error when the search button
    // attempts to invoke main. Should get them both to call common code 
    def search()
    {
        params.max = Math.min(params.max ? params.int('max') : ROWS_PER_PAGE, 100)
        
        ElectoralRoll roll = ElectoralRoll.get (params.id)
        
        def entries = electoralRollService.getEntries (roll, params)
        
//        def rolls = electoralRollService.getAllRolls()
        def rolls = electoralRollService.getLatestRolls()
        
        render (view: "main",
        model:
        [currentRoll: roll?.displayString ?: "",
        rolls: rolls,
         electoralRollEntryInstanceList: entries, 
         electoralRollEntryInstanceTotal: entries.totalCount])
    }
    
    def createReport()
    {
        ElectoralRoll roll = ElectoralRoll.get (params.id)
        
        def entries = electoralRollService.getEntries (roll, params)
  
        def out = new File('/downloads/greendb.csv')
        out.delete()
        
        out.append "Ref,Surname,First Names,Address\n"

        entries.each 
        {
            def row = [it.ref, it.person.surname, it.person.firstNames, it.address.getSingleLine()]
                                 .collect { '"' + it.replace('"','""') + '"' }
            out.append row.join(',')
            out.append '\n'
        }        
        
        redirect(action: "search", params: params)
//        chain(controller:'jasper',action:'index',model:[data:entries],params:params)
    }    
    
    def list() 
    {
//        log.error (params)
        
        params.max = Math.min(params.max ? params.int('max') : ROWS_PER_PAGE, 100)
        
        ElectoralRoll roll = ElectoralRoll.get (params.id)
        
        def entries = electoralRollService.getEntries (roll, params)
        
        [electoralRollEntryInstanceList: entries, 
         electoralRollEntryInstanceTotal: entries.totalCount]
    }

    // ?? this is exactly the same as list, because I get an error when the search button
    // attempts to invoke list. Should get them both to call common code 
//    def search() 
//    {
////        log.error (params)
//        
//        params.max = Math.min(params.max ? params.int('max') : ROWS_PER_PAGE, 100)
//        
//        ElectoralRoll roll = ElectoralRoll.get (params.id)
//        
//        def entries = electoralRollService.getEntries (roll, params)
//        
//        render (view: "list",
//        model:
//        [electoralRollEntryInstanceList: entries, 
//         electoralRollEntryInstanceTotal: entries.totalCount])
//    }

    def advancedSearch()
    {
        render (view: "search_form")
        
    }
    
    def create() {
        [electoralRollEntryInstance: new ElectoralRollEntry(params)]
    }

    def save() {
        def electoralRollEntryInstance = new ElectoralRollEntry(params)
        if (!electoralRollEntryInstance.save(flush: true)) {
            render(view: "create", model: [electoralRollEntryInstance: electoralRollEntryInstance])
            return
        }

		flash.message = message(code: 'default.created.message', args: [message(code: 'electoralRollEntry.label', default: 'ElectoralRollEntry'), electoralRollEntryInstance.id])
        redirect(action: "show", id: electoralRollEntryInstance.id)
    }

    def show() {
        def electoralRollEntryInstance = ElectoralRollEntry.get(params.id)
        if (!electoralRollEntryInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'electoralRollEntry.label', default: 'ElectoralRollEntry'), params.id])
            redirect(action: "list")
            return
        }

        [electoralRollEntryInstance: electoralRollEntryInstance]
    }

    def edit() {
        def electoralRollEntryInstance = ElectoralRollEntry.get(params.id)
        if (!electoralRollEntryInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'electoralRollEntry.label', default: 'ElectoralRollEntry'), params.id])
            redirect(action: "list")
            return
        }

        [electoralRollEntryInstance: electoralRollEntryInstance]
    }

    def update() {
        def electoralRollEntryInstance = ElectoralRollEntry.get(params.id)
        if (!electoralRollEntryInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'electoralRollEntry.label', default: 'ElectoralRollEntry'), params.id])
            redirect(action: "list")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (electoralRollEntryInstance.version > version) {
                electoralRollEntryInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'electoralRollEntry.label', default: 'ElectoralRollEntry')] as Object[],
                          "Another user has updated this ElectoralRollEntry while you were editing")
                render(view: "edit", model: [electoralRollEntryInstance: electoralRollEntryInstance])
                return
            }
        }

        electoralRollEntryInstance.properties = params

        if (!electoralRollEntryInstance.save(flush: true)) {
            render(view: "edit", model: [electoralRollEntryInstance: electoralRollEntryInstance])
            return
        }

		flash.message = message(code: 'default.updated.message', args: [message(code: 'electoralRollEntry.label', default: 'ElectoralRollEntry'), electoralRollEntryInstance.id])
        redirect(action: "show", id: electoralRollEntryInstance.id)
    }

    def delete() {
        def electoralRollEntryInstance = ElectoralRollEntry.get(params.id)
        if (!electoralRollEntryInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'electoralRollEntry.label', default: 'ElectoralRollEntry'), params.id])
            redirect(action: "list")
            return
        }

        try {
            electoralRollEntryInstance.delete(flush: true)
			flash.message = message(code: 'default.deleted.message', args: [message(code: 'electoralRollEntry.label', default: 'ElectoralRollEntry'), params.id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
			flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'electoralRollEntry.label', default: 'ElectoralRollEntry'), params.id])
            redirect(action: "show", id: params.id)
        }
    }
}
